package com.mimiwang.common.utils;

import org.springframework.boot.system.ApplicationHome;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @AUTHOR:游李滨
 * @DATE:2022/8/17 12:21
 */
public class NetworkUtils {

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，那么取第一个ip为客户端ip
        if (ip != null && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }

        return ip;
    }
    /**
     *  url转换成本地资源路径
     *  参数：String packagePath   例如: /static
     *
     * */

    public static String urlToLocal(String packagePath,String url){
        int minUrlLength=15;
        if(url.length() < minUrlLength){
            return "";
        }
//        fileName 如:/image/CE.jpg
        String fileName=url.substring(url.indexOf("/",minUrlLength));
//      如： E://Server/static                   +   fileName
        return getAppPath()+packagePath+fileName;
    }

    /**
     *  获取jar包所在目录
     *
     *  返回值:
     *      例如: E://server
     * */

    public static String getAppParentPath(){
        return getAppFile().getParent();
    }
    public static String getAppPath(){
        File appFile = getAppFile();
//        基础路径为jar包父路径
        return appFile.getPath();
    }
    public static File getAppFile(){
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(NetworkUtils.class);
       return h.getSource();
    }

}
